import UIKit
import BUAdSDK
import AdSupport
import AppTrackingTransparency


class AdController: UIViewController,BUSplashAdDelegate {
    
    var onClose: (() -> Void)? // 定义一个闭包属性，用于保存页面关闭时的回调函数
        
    // 页面关闭时调用此方法
    func closePage() {
        onClose?()
    }

    var adView :UIView?
//    var splashAd : BUSplashAd?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        let screenWidth = UIScreen.main.bounds.width
        let screenHeight = UIScreen.main.bounds.height
        var bottomSafeAreaInset = 0.0
        if let window = UIApplication.shared.windows.first {
            bottomSafeAreaInset = window.safeAreaInsets.bottom
        }
        
        adView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight - bottomSafeAreaInset - 100))
//        adView?.backgroundColor = .green

        // 创建图片
        let imageView = UIImageView(frame: CGRect(x: (screenWidth - 60)/2, y: 20, width: 60, height: 60))
        imageView.contentMode = .scaleAspectFit
        if let infoDict = Bundle.main.infoDictionary,
           let bundleIcons = infoDict["CFBundleIcons"] as? [String: Any],
           let primaryIcon = bundleIcons["CFBundlePrimaryIcon"] as? [String: Any],
           let iconFiles = primaryIcon["CFBundleIconFiles"] as? [String],
           let lastIconFile = iconFiles.last {
            imageView.image = UIImage(named: lastIconFile)
        }

        // 将图片放在父容器中
        let imagePaarentView = UIView(frame: CGRect(x: 0, y: screenHeight - bottomSafeAreaInset - 100, width: screenWidth, height: 100))
        imagePaarentView.addSubview(imageView)

        // 底部安全距离
        let bottomSafeArea = UIView(frame: CGRect(x: 0, y: screenHeight - bottomSafeAreaInset, width: screenWidth, height: bottomSafeAreaInset))

        if let adView = adView {
            view.addSubview(adView)
        }
        view.addSubview(imagePaarentView)
        view.addSubview(bottomSafeArea)
        
        requestIDFAAuthorization()
    }
    
    // 检查是否支持请求授权
    func requestIDFAAuthorization() {
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { status in
                switch status {
                case .authorized: // 用户已授权，可以获取 IDFA
                    let advertisingIdentifier = ASIdentifierManager.shared().advertisingIdentifier
                    print("111111111111111111, IDFA: \(advertisingIdentifier)")
                    self.initAd()
                case .denied, .restricted: // 用户拒绝了授权或者限制了广告跟踪，需要提醒用户去设置中允许
                    self.closeUi()
                    print("111111111111111111, 用户拒绝了授权IDFA")
                case .notDetermined: // 用户还未做出选择，可以再次请求授权
                    print("111111111111111111, 用户还未做出选择")
                    self.closeUi()
                @unknown default:
                    self.closeUi()
                }
            }
        } else { // iOS 14 以下版本，不需要请求授权，直接获取 IDFA
            let advertisingIdentifier = ASIdentifierManager.shared().advertisingIdentifier
            print("IDFA: \(advertisingIdentifier)")
            self.initAd()
        }
    }
    
    /******************** 初始化 ********************/
    @objc func initAd() {
        let configuration = BUAdSDKConfiguration()
        configuration.appID = "5538224" // 设置APPID 5524370 android的   5538224 iOS的
        configuration.debugLog = true // 设置日志输出
        configuration.useMediation = false // 是否使用聚合

        // 初始化
        BUAdSDKManager.start(asyncCompletionHandler:{ success, error in
            if success { // 处理成功之后的逻辑
                print("---------------------------------------------------------\n SDK初始化成功")
                self.loadSplashAd()
            } else{
                self.closeUi()
            }
        })
    }
    
    /******** 开屏广告配置 *********/
    func loadSplashAd() -> Void {
        let slot = BUAdSlot()
        slot.id = "889243899"
        splashAd = BUSplashAd(slot: slot, adSize: CGSize.zero)
        splashAd?.delegate = self
        splashAd?.loadData()
    }
    
    /******** 开屏广告回调处理 *********/
    // 加载成功
    func splashAdLoadSuccess(_ splashAd: BUSplashAd) {
        // 使用应用keyWindow的rootViewController（接入简单，推荐）
        splashAd.showSplashView(inRootViewController: self)
        
        print("1111111111111111111111, 加载成功")

    }

    // 加载失败
    func splashAdLoadFail(_ splashAd: BUSplashAd, error: BUAdError?) {
        print("1111111111111111111111, 加载失败")
        print(error ?? "没用错误信息")
        closeUi()
    }

    // 广告即将展示
    func splashAdWillShow(_ splashAd: BUSplashAd) {
        print("1111111111111111111111, 广告即将展示")
    }

    // 广告被点击
    func splashAdDidClick(_ splashAd: BUSplashAd) {
        print("1111111111111111111111, 广告被点击")
    }

    // 广告被关闭
    func splashAdDidClose(_ splashAd: BUSplashAd, closeType: BUSplashAdCloseType) {
        // 按照实际情况决定是否销毁广告对象
        splashAd.mediation?.destoryAd()
        print("1111111111111111111111, 广告被关闭")
        closeUi()
    }

    // 广告展示失败
    func splashAdDidShowFailed(_ splashAd: BUSplashAd, error: Error) {
        print("1111111111111111111111, 广告展示失败")
        closeUi()
    }

    // 广告渲染完成
    func splashAdRenderSuccess(_ splashAd: BUSplashAd) {
        print("1111111111111111111111, 广告渲染完成")
    }

    // 广告渲染失败
    func splashAdRenderFail(_ splashAd: BUSplashAd, error: BUAdError?) {
        print("1111111111111111111111, 广告渲染失败")
        closeUi()
    }

    // 广告展示
    func splashAdDidShow(_ splashAd: BUSplashAd) {
        print("1111111111111111111111, 广告展示")
    }

    // 广告控制器被关闭
    func splashAdViewControllerDidClose(_ splashAd: BUSplashAd) {
        print("1111111111111111111111, 广告控制器被关闭")
        closeUi()
    }

    // 其他控制器被关闭
    func splashDidCloseOtherController(_ splashAd: BUSplashAd, interactionType: BUInteractionType) {
        print("1111111111111111111111, 其他控制器被关闭")
    }

    // 视频播放完成
    func splashVideoAdDidPlayFinish(_ splashAd: BUSplashAd, didFailWithError error: Error?) {
        print("1111111111111111111111, 视频播放完成")
        closeUi()
    }
    
    @objc func closeUi() {
        self.dismiss(animated: true, completion: nil)
        closePage()
    }
}
